myApp_.onPageInit('shoppingcar', function (page) {
    SHOPPING_CAR.user_cart();
});

//购物车
SHOPPING_CAR = {};
SHOPPING_CAR.data = {};
SHOPPING_CAR.order_data = {};

SHOPPING_CAR.is_load = false;

SHOPPING_CAR.__INIT__ = function () {
    SHOPPING_CAR.jump();
}

SHOPPING_CAR.jump = function () {
    mainView.router.load({
        url: "src/index/shoppingcar/shoppingcar.html"
    });
};
SHOPPING_CAR.order_jump = function () {
    var context = SHOPPING_CAR.order_data;
    mainView.router.load({
        url: "src/index/shoppingcar/make_order.html",
        context: context
    });
};
/*
 * 用户购物车 
 */
SHOPPING_CAR.user_cart = function () {
    var url = url_('api/V1/user_cart');
    var data = {'community_id': SESSION.get_community_id()};
    var success = function (d) {
        if (d.code == 0) {
            if (d.data.length == 0) {
                d.is_empty = true;
            }
            SHOPPING_CAR.data = d;
            SHOPPING_CAR.fill_cart();
        } else if (d.code == 1011) {
            my_tips_(d.msg, function () {
                go_("login");
            })
        } else {
            my_tips_(d.msg);
        }
    }
    request_(url, data, success)
}
/**
 * 渲染购物车
 */
SHOPPING_CAR.fill_cart = function () {
    $.tpl({
        url: "src/index/shoppingcar/shoppingcar_tpl.html"
        , context: SHOPPING_CAR.data
        , elem: ".shopping_car_cart_container"
        , after: function () {
            TotalPrice();//计算总价
        }
    });
    user_cart_count();//购物车上角标
}

/*
 * 购物车前往下单
 */
SHOPPING_CAR.cart_to_order = function () {
    var cart_id = [];
    $('input.goodsCheck:checked').each(function (i, e) {
        cart_id[i] = $(e).parents('div[name="goods_content"]').data('id');
    });
    if (cart_id.length == 0) {
        my_tips_('没有选择商品');
        return;
    }

    var url = url_('api/V2/cart_to_order');
    var data = {'cart_id': cart_id, "community_id": SESSION.get_community_id()};
    var success = function (d) {
        if (d.code == 0) {
            SHOPPING_CAR.create_order();
        } else if (d.code == 1011) {
            my_tips_(d.msg, function () {
                go_("login");
            })
        } else {
            my_tips_(d.msg);
        }
    }
    request_(url, data, success)
}

/*
 * 提交成功后前往生成订单页面所需要的数据
 */
SHOPPING_CAR.create_order = function () {
    var url = url_('api/V2/create_order');
    var data = {"community_id": SESSION.get_community_id()};
    var success = function (d) {
        if (d.code == 0) {
            //处理订单数据
            //筛选地址处理
            var addrs = d.data.address;
            if(addrs[0]){
                d.data.address = addrs[0];
            }else{
                d.data.address = false;
            }
            //for (var i in addrs) {
            //    if (1) {
            //        d.data.address = addrs[i];
            //        break;
            //    } else {//如果没有默认地址则提示选择地址
            //        d.data.address = false;
            //    }
            //}
            //计算总价
            var goods = d.data.goods;
            var total = 0;
            for (var i in goods) {
                total += (parseFloat(goods[i].good.price) * 100 * parseInt(goods[i].count)) / 100;
            }
            d.data.total_price = total.toFixed(2);
            SHOPPING_CAR.order_data = d.data;
            SHOPPING_CAR.order_jump();
        } else if (d.code == 1011) {
            my_tips_(d.msg, function () {
                go_("login");
            })
        } else {
            my_tips_(d.msg);
        }
    }
    request_(url, data, success)
}

/**
 * 选择收货地址
 */
SHOPPING_CAR.check_address = function () {
    go_('address');
}
/*
 * 下单
 */
SHOPPING_CAR.create_order_data = function () {
    var address_id = $('.shouhuo_area').data('address_id');
    var memo = $('.order_memo').val();
    var ziti_type = 0;//配送方式 0自提 1配送
    var songhuo = $('#songhuo');
    if (songhuo.hasClass('active')) {
        ziti_type = 1;
    }

    var url = url_('api/V2/create_order_data');
    var data = {
        'address_id': address_id,
        'ziti_type': ziti_type,
        'community_id': SESSION.get_community_id(),
        'memo': memo
    };
    var success = function (d) {
        if (d.code == 0) {
            var r_data = d.data;
            go_("pay/" + r_data.code + "/" + r_data.fee);
        } else if (d.code == 1011) {
            my_tips_(d.msg, function () {
                go_("login");
            })
        } else {
            my_tips_(d.msg);
        }
    }
    request_(url, data, success)
}


/*
 * *********************************************************工具函数***************************************************************************
 */
/*编辑操作*/
function edit_cart_(e, quantity) {
    var btn = $(e);
    if (btn.attr('name') == 'edit') {
        btn.html("完成");
        btn.attr('name', 'complete');
        btn.parents("li").find(".item-cart-tan").show();
        btn.parents('li').siblings().find(".item-cart-tan").hide();
        btn.parents('li').siblings().find(".p-right").html("编辑");
        btn.parents('li').siblings().find(".p-right").attr('name', 'edit');
    } else if (btn.attr('name') == 'complete') {
        var id = btn.data('goods_id');
        var curr_count = btn.parents('li').find('input[name="goods_count"]').val();
        if (curr_count <= 0) {
            myApp_.alert('请填写大于0的数量', '提示');
            return;
        }
        btn.html("编辑");
        btn.attr('name', 'edit');
        btn.parents("li").find(".item-cart-tan").hide();
        var change = curr_count - quantity;
        if (change == 0) {
            return;
        }
        add_cart_(2, id, change);
    }
}

/*删除购物车方法*/
function del_cart(id) {
    myApp_.confirm('确定要将此商品移除购物车吗？', function () {
        var url = url_('api/V1/del_cart');
        var data = {goods_id: id};
        var success = function (data) {
            if (data.code == 0) {
                SHOPPING_CAR.user_cart();
            } else {
                my_tips_(d.msg);
            }
        }
        request_(url, data, success);
    });
}

/******---------------------------------------------------------------分割线--------------------------------------------------------------------******/
// 点击商品按钮
function good_btn(obj) {
    if ($(".goodsCheck").length == $(".goodsCheck:checked").length) { //如果店铺被选中的数量等于所有店铺的数量
        $("#AllCheck").prop('checked', true); //全选按钮被选中
        TotalPrice();
    } else {
        $("#AllCheck").prop('checked', false); //else全选按钮不被选中 
        TotalPrice();
    }
};

// 点击全选按钮
function all_btn(obj) {
    if ($(obj).prop("checked") == true) { //如果全选按钮被选中
        $(".goods-check").prop('checked', true); //所有按钮都被选中
        TotalPrice();
    } else {
        $(".goods-check").prop('checked', false); //else所有按钮不全选
        TotalPrice();
    }
    $(".shopCheck").change(); //执行店铺全选的操作
};

function TotalPrice() {
    var allprice = 0; //总价
    if ($("li").length == 0) {
        $('#cart_empty').show();
    }
    $("ul#shopping-content li").each(function () { //循环每个店铺
        var oprice = 0; //店铺总价
        $(this).find(".goodsCheck").each(function () { //循环店铺里面的商品
            if ($(this).is(":checked")) { //如果该商品被选中
                var num = parseInt($(this).parents("li").find('span[name="goods_count"]').text()); //得到商品的数量
                var price = parseFloat($(this).parents("li").find(".danjia span").text()); //得到商品的单价
                var total = price * num; //计算单个商品的总价

                oprice += total; //计算该店铺的总价
            }
        });
        allprice += oprice; //计算所有店铺的总价
    });
    $(".shopping_jiesuan_total span").text(allprice.toFixed(2)); //输出全部总价
}

